/**
 * There are <a href="https://github.com/thinkgem/jeesite">JeeSite</a> code generation
 */
package com.boxin.ims.modules.wechat.web;

import java.io.File;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.boxin.ims.modules.wechat.entity.BusinessConfig;
import com.boxin.ims.modules.wechat.entity.BusinessNewsReply;
import com.boxin.ims.modules.wechat.entity.UserBusiness;
import com.boxin.ims.modules.wechat.entity.WechatBusiness;
import com.boxin.ims.modules.wechat.service.BusinessConfigService;
import com.boxin.ims.modules.wechat.service.BusinessNewsReplyService;
import com.boxin.ims.modules.wechat.service.UserBusinessService;
import com.boxin.ims.modules.wechat.service.WechatBusinessService;
import com.boxin.ims.modules.wechat.utils.WechatUtils;
import com.google.common.collect.Maps;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.utils.FileUtils;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;

/**
 * 用户业务服务定义类Controller
 * @author Jakemanse
 * @version 2013-09-27
 */
@Controller
@RequestMapping(value = Global.ADMIN_PATH+"/wechat/userBusiness")
public class UserBusinessController extends BaseController {

	@Autowired
	private UserBusinessService userBusinessService;
	
	@Autowired
	private BusinessConfigService businessConfigService;
	
	
	@Autowired
	private WechatBusinessService wechatBusinessService;
	
	@Autowired
	BusinessNewsReplyService businessNewsReplyService;
	
	@ModelAttribute
	public UserBusiness get(@RequestParam(required=false) Long id) {
		if (id != null){
			return userBusinessService.get(id);
		}else{
			return new UserBusiness();
		}
	}
	
	@RequiresPermissions("wechat:userBusiness:view")
	@RequestMapping(value = {"list", ""})
	public String list(UserBusiness userBusiness, HttpServletRequest request, HttpServletResponse response, Model model) {
		
		User user = UserUtils.getUser();
		if (!user.isAdmin()){
			userBusiness.setUser(user);
		}
		
		
		
        Page<UserBusiness> page = userBusinessService.find(new Page<UserBusiness>(request, response), userBusiness); 
        model.addAttribute("page", page);
        model.addAttribute("userBusiness", userBusiness);
        
		return "modules/wechat/userBusinessList";
	}
	
	
	private UserBusiness getUserBusinessByConfigId(List<UserBusiness> businessList,Long configId){
		for(UserBusiness ubus : businessList){
			Long id = ubus.getBusinessConfig().getId();
			if(id == configId){
				return ubus;
			} 
		}
		
		return new UserBusiness();
	}

	@RequiresPermissions("wechat:userBusiness:view")
	@RequestMapping(value = "form")
	public String form(UserBusiness userBusiness, Model model) {
		User user = UserUtils.getUser();
		List<BusinessConfig> configList = 	businessConfigService.findAll();	//所有服务配置
		List<UserBusiness> businessList = userBusinessService.findAllByUserId(user.getId());
		
//		for(BusinessConfig config : configList){
//			Long configId = config.getId();
//			UserBusiness userBusiness2 = getUserBusinessByConfigId(businessList,configId);
//			if(userBusiness2.getId()==null){
//				userBusiness2.setBusinessConfig(config);
//				userBusiness2.setUser(user);
//				businessList.add(userBusiness2);
//			}
//		}
		
		/////
		//多图文列表
		List<BusinessNewsReply> newsReplyList = businessNewsReplyService.findByTypeSourceId(BusinessNewsReply.MSG_TYPE_BUSINESS,user.getId(), userBusiness.getId()+"");
		model.addAttribute("newsReplyList", newsReplyList);
		
		
		userBusiness.setUser(UserUtils.getUser());
		model.addAttribute("configList", configList);
		model.addAttribute("businessList", businessList);
		return "modules/wechat/userBusinessForm";
	}
	
	
	@RequiresPermissions("wechat:userBusiness:view")
	@RequestMapping(value = "getUserBusiness")
	public void getUserBusiness(  HttpServletRequest request, HttpServletResponse response, Model model){
		
		String uid = request.getParameter("userId");
		String cid = request.getParameter("configId");
		
		UserBusiness userBusiness = userBusinessService.getByUserIdAndConfigId(Long.parseLong(uid), Long.parseLong(cid));
		Map<String, String> params = Maps.newHashMap();
		userBusiness = (userBusiness==null) ? new UserBusiness() :userBusiness;
		params.put("id", userBusiness.getId()+"");
		params.put("content", userBusiness.getContent());
		params.put("userId", uid);
		writeJson(request, response, params);	
		
	}

	@RequiresPermissions("wechat:userBusiness:edit")
	@RequestMapping(value = "save")
	public String save(@RequestParam("picfile") MultipartFile picfile,UserBusiness userBusiness,HttpServletRequest request, HttpServletResponse response, Model model,  RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, userBusiness)){
			return form(userBusiness, model);
		}
		
		if(userBusiness.getId() == null){
			UserBusiness temp = userBusinessService.getByUserIdAndConfigId(userBusiness.getUser().getId(), userBusiness.getBusinessConfig().getId());
			if(temp != null){
				userBusiness.setId(temp.getId());
			}
		}
		
		
		userBusinessService.save(userBusiness);
		
		String title = request.getParameter("title");
		String url = request.getParameter("url");
		String picDesc = request.getParameter("description");
		
		BusinessNewsReply reply = new BusinessNewsReply();
		
		reply.setDescription(picDesc);
		reply.setTitle(title);
		reply.setUrl(url);
		reply.setType(BusinessNewsReply.MSG_TYPE_BUSINESS);
		reply.setPicUrl(null);
		reply.setSourceId(userBusiness.getId()+"");
		reply.setUser(userBusiness.getUser());
		
		
		if(picfile != null && picfile.getOriginalFilename().length()>4){
			String businessPath = WechatUtils.getWechatUserBusinessResourceSavePath(request) + File.separator;
			FileUtils.createDirectory(businessPath);
			String sname = picfile.getOriginalFilename();
			String fileType = sname.substring(sname.lastIndexOf("."));
			String fname  = UserUtils.getUser().getLoginName()+	"_business_"+System.currentTimeMillis()+fileType;
			File file = new File(businessPath+fname);
			System.out.println("保存文件:"+businessPath+fname);
			try {
				picfile.transferTo(file);
				reply.setFilePath(fname);
			} catch (Exception e) {
				System.out.println("上传文件失败:"+businessPath+fname);
				e.printStackTrace();
			}
			
		}
		
		
		
		
		businessNewsReplyService.save(reply);	//保存
		
		
		addMessage(redirectAttributes, "保存成功");
		return "redirect:"+Global.ADMIN_PATH+"/wechat/userBusiness/?repage";
	}
	
	@RequiresPermissions("wechat:userBusiness:edit")
	@RequestMapping(value = "delete")
	public String delete(Long id, RedirectAttributes redirectAttributes) {
		userBusinessService.delete(id);
		addMessage(redirectAttributes, "删除用户业务服务定义类成功");
		return "redirect:"+Global.ADMIN_PATH+"/wechat/userBusiness/?repage";
	}

}
